package com.worthtech.billportal.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class SendMsg {

	String msg = null;
	String serverip;
	String serverport;
	int timeout = 10;
	public String data;
	File file = new File(Constant.ROOTPATH + "WEB-INF/BillPort.txt");

	public void init() throws Exception {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file));
			BufferedReader reader = new BufferedReader(read);
			String str = new String();
			int i = 0;
			while ((str = reader.readLine()) != null) {
				if (!str.startsWith("#")) {
					if (i == 0) {
						serverip = str;
					}
					if (i == 1) {
						serverport = str;
					}
					i++;
				}
			}
	}

	public SendMsg(String msg)  {
		this.msg = msg;
		this.start();
	}
	public void start(){
		this.run();
	}
	public String getData(){
		return this.data;
	}
	public void run(){
			try {
				init();
				Socket s=null;
				for(int i = 0;i<timeout;i++){
					try {
						s = new Socket(serverip, Integer.valueOf(serverport));
						break;
					} catch (Exception e1) {
						Thread.sleep(1000);
					}
				}
				s.setKeepAlive(true);
				s.setSoTimeout(5000);
				System.out.println("keeplive=" + s.getKeepAlive());
				System.out.println("isConnected=" + s.isConnected());
				DataOutputStream out = new DataOutputStream(s.getOutputStream());
				InputStream is = s.getInputStream();
				System.out.println("get outStream");
				out.write(msg.getBytes("gb2312"));
				System.out.println("write data");
				out.flush();
				byte b[] = new byte[1024];
				is.read(b);
				String str = new String(b);
				System.out.println("data=" + str);
				if(str==null)
					str="";
				if(!str.trim().equals("")){
					try {
						data = str.substring(59, 61);
					} catch (RuntimeException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						data = null;
					}
				}
				s.setKeepAlive(false);
				s.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				data=null;
			}
	}

	public void setData(String data) {
		this.data = data;
	}
}
